package com.wfyn.reggie.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfyn.reggie.common.web.domain.Result;
import com.wfyn.reggie.common.web.exception.base.BusinessException;
import com.wfyn.reggie.modules.sys.domain.Category;
import com.wfyn.reggie.modules.sys.domain.Dish;
import com.wfyn.reggie.modules.sys.domain.Setmeal;
import com.wfyn.reggie.modules.sys.param.PageListRequest;
import com.wfyn.reggie.modules.sys.service.CategoryService;
import com.wfyn.reggie.modules.sys.mapper.CategoryMapper;
import com.wfyn.reggie.modules.sys.service.DishService;
import com.wfyn.reggie.modules.sys.service.SetmealService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author wfyn
* @description 针对表【category(菜品及套餐分类)】的数据库操作Service实现
* @createDate 2023-09-25 15:59:00
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    DishService dishService;
    @Autowired
    SetmealService setmealService;

    @Override
    public Result<Page<Category>> categoryPage(PageListRequest pageListRequest) {

        //分页构造器
        Page<Category> pageInfo = new Page<>(pageListRequest.getPage(), pageListRequest.getPageSize());

        //分页并排序
        this.page(pageInfo, new LambdaQueryWrapper<Category>()
                .like(StringUtils.isNotEmpty(pageListRequest.getName()), Category::getName, pageListRequest.getName())
                .orderByAsc(Category::getSort))
                ;


        return Result.success(pageInfo);
    }

    @Override
    public boolean deleteCategory(Long id) {

        long count1 = dishService.count(new LambdaQueryWrapper<Dish>()
                .eq(Dish::getCategoryId, id));
        if(count1>0)
        {
            throw new BusinessException("菜品分类下有菜品，不能删除");
        }

        long count2 = setmealService.count(new LambdaQueryWrapper<Setmeal>()
                .eq(Setmeal::getCategoryId, id));
        if(count2>0)
        {
            throw new BusinessException("菜品分类下有套餐，不能删除");
        }

        return removeById(id);


    }


}




